package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author zsk
 * @create 2022-02-27-21:42
 */
@RestController
public class EmployeeController {

    //依赖注入
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    /*
    登录请求
    Request URL: http://localhost:8080/employee/login
    Request Method: POST
     */
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {

        //接收参数
        String username = map.get("username");
        String password = map.get("password");

        //调用service层查询
        ResultInfo resultInfo = employeeService.login(username, password);

        //如果登录成功，则保存到session对象中
        if (resultInfo.getCode() == 1) {
            //先把返回的信息转换成Employee数据
            Employee employee = (Employee) resultInfo.getData();
            //存储到session中
            session.setAttribute("SESSION_EMPLOYEE",employee);
        }
        //返回结果
        return resultInfo;
    }

    //用户退出
    /*
    Request URL: http://localhost:8080/employee/logout
    Request Method: POST
     */
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //删除掉session存储的数据
        session.invalidate();

        //返回结果
        return ResultInfo.success(null);
    }

    /*
    查询用户列表
    Request URL: http://localhost:8080/employee/find?name=%E5%BC%A0
    Request Method: GET
     */
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name){

        //调用service层查询
        List<Employee> employeeList = employeeService.findByName(name);

        //返回结果
        return ResultInfo.success(employeeList);

    }

    /*
    添加用户信息
    Request URL: http://localhost:8080/employee
    Request Method: POST
     */
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){

        //调用service保存
        employeeService.save(employee);

        //返回结果
        return ResultInfo.success(null);
    }

    /*
    编辑前回显信息
    Request URL: http://localhost:8080/employee/1
    Request Method: GET
     */
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        //调用service层查询
        Employee employee = employeeService.findById(id);
        //返回结果
        return ResultInfo.success(employee);
    }

    /*
    修改数据
    Request URL: http://localhost:8080/employee
    Request Method: PUT
     */
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){

        //调用service修改
        employeeService.update(employee);
        //返回结果
        return ResultInfo.success(null);

    }


}
